-- @preview-file on clear

-- CombatDamageSystem.lua
-- 战斗伤害检测系统：处理玩家与敌人的伤害检测

local CombatDamageSystem = {}
CombatDamageSystem.__index = CombatDamageSystem

function CombatDamageSystem.new()
    local instance = {
        -- 攻击检测区域
        attackZones = {},
        
        -- 伤害配置
        damageConfig = {
            player = {
                chi = { base = 30, combo = 5 },      -- 剑模式
                chui = { base = 40, combo = 8 },     -- 锤模式
                zao = { base = 50, combo = 10 }      -- 凿模式
            },
            enemy = {
                sword = 20,      -- 剑士伤害
                archer = 15,     -- 弓箭手伤害
                broadsword = 35, -- 刀兵伤害
                boss = 50        -- Boss伤害
            }
        },
        
        -- 状态
        activeAttacks = {},
        attackCooldowns = {},
        
        -- 调试模式
        debugMode = true
    }
    
    return setmetatable(instance, CombatDamageSystem)
end

-- 注册玩家攻击
function CombatDamageSystem:registerPlayerAttack(playerId, position, facingRight, weaponMode, comboNumber)
    local attackId = playerId .. "_attack_" .. os.time()
    
    -- 计算伤害
    local baseDamage = self.damageConfig.player[weaponMode].base
    local comboBonus = self.damageConfig.player[weaponMode].combo * (comboNumber - 1)
    local totalDamage = baseDamage + comboBonus
    
    -- 创建攻击区域
    local attackWidth = 100 + comboNumber * 20  -- 连击数越多攻击范围越大
    local attackHeight = 60
    local offsetX = facingRight and 50 or -50
    
    local attackZone = {
        id = attackId,
        owner = playerId,
        type = "player_attack",
        x = position.x + offsetX,
        y = position.y,
        width = attackWidth,
        height = attackHeight,
        damage = totalDamage,
        facingRight = facingRight,
        startTime = os.time(),
        duration = 0.3,  -- 攻击持续0.3秒
        isActive = true
    }
    
    self.activeAttacks[attackId] = attackZone
    
    if self.debugMode then
        print(string.format("玩家攻击注册: 伤害=%d, 位置=(%.1f,%.1f), 范围=%dx%d, 面向=%s",
            totalDamage, attackZone.x, attackZone.y, attackWidth, attackHeight,
            facingRight and "右" or "左"))
    end
    
    return attackZone
end

-- 注册敌人攻击
function CombatDamageSystem:registerEnemyAttack(enemyId, enemyType, position, facingRight)
    local attackId = enemyId .. "_attack_" .. os.time()
    local damage = self.damageConfig.enemy[enemyType] or 20
    
    -- 敌人攻击区域（根据类型不同）
    local attackWidth, attackHeight = 80, 60
    local offsetX = facingRight and 40 or -40
    
    if enemyType == "archer" then
        -- 弓箭手：远程攻击
        attackWidth = 200
        attackHeight = 30
        offsetX = facingRight and 100 or -100
    elseif enemyType == "boss" then
        -- Boss：大范围攻击
        attackWidth = 150
        attackHeight = 100
        offsetX = facingRight and 80 or -80
    end
    
    local attackZone = {
        id = attackId,
        owner = enemyId,
        type = "enemy_attack",
        enemyType = enemyType,
        x = position.x + offsetX,
        y = position.y,
        width = attackWidth,
        height = attackHeight,
        damage = damage,
        facingRight = facingRight,
        startTime = os.time(),
        duration = 0.4,  -- 敌人攻击持续0.4秒
        isActive = true
    }
    
    self.activeAttacks[attackId] = attackZone
    
    if self.debugMode then
        print(string.format("敌人攻击注册: %s, 伤害=%d, 位置=(%.1f,%.1f)",
            enemyType, damage, attackZone.x, attackZone.y))
    end
    
    return attackZone
end

-- 检查攻击是否命中
function CombatDamageSystem:checkAttackHit(attackId, targetId, targetX, targetY, targetRadius)
    local attack = self.activeAttacks[attackId]
    if not attack or not attack.isActive then
        return false, 0
    end
    
    -- 计算目标边界
    local targetLeft = targetX - targetRadius
    local targetRight = targetX + targetRadius
    local targetTop = targetY + targetRadius
    local targetBottom = targetY - targetRadius
    
    -- 计算攻击区域边界
    local attackLeft = attack.x - attack.width / 2
    local attackRight = attack.x + attack.width / 2
    local attackTop = attack.y + attack.height / 2
    local attackBottom = attack.y - attack.height / 2
    
    -- 检测矩形相交
    local hit = not (targetRight < attackLeft or 
                    targetLeft > attackRight or 
                    targetBottom > attackTop or 
                    targetTop < attackBottom)
    
    if hit and self.debugMode then
        print(string.format("攻击命中: %s -> %s, 伤害=%d",
            attack.owner, targetId, attack.damage))
    end
    
    return hit, hit and attack.damage or 0
end

-- 检查玩家是否被敌人攻击
function CombatDamageSystem:checkPlayerUnderAttack(playerX, playerY, playerRadius)
    for attackId, attack in pairs(self.activeAttacks) do
        if attack.type == "enemy_attack" and attack.isActive then
            local hit, damage = self:checkAttackHit(attackId, "player", playerX, playerY, playerRadius)
            if hit then
                return true, damage, attack.owner
            end
        end
    end
    
    return false, 0, nil
end

-- 检查敌人是否被玩家攻击
function CombatDamageSystem:checkEnemyUnderAttack(enemyId, enemyX, enemyY, enemyRadius)
    for attackId, attack in pairs(self.activeAttacks) do
        if attack.type == "player_attack" and attack.isActive then
            local hit, damage = self:checkAttackHit(attackId, enemyId, enemyX, enemyY, enemyRadius)
            if hit then
                return true, damage, attack.owner
            end
        end
    end
    
    return false, 0, nil
end

-- 更新攻击状态（清理过期攻击）
function CombatDamageSystem:update(dt)
    local currentTime = os.time()
    local toRemove = {}
    
    for attackId, attack in pairs(self.activeAttacks) do
        if attack.isActive then
            -- 检查攻击是否过期
            if currentTime - attack.startTime > attack.duration then
                attack.isActive = false
                table.insert(toRemove, attackId)
            end
        elseif currentTime - attack.startTime > attack.duration * 2 then
            -- 完全移除过期的攻击
            table.insert(toRemove, attackId)
        end
    end
    
    for _, attackId in ipairs(toRemove) do
        self.activeAttacks[attackId] = nil
    end
end

-- 清理所有攻击
function CombatDamageSystem:clearAllAttacks()
    self.activeAttacks = {}
end

-- 重置系统
function CombatDamageSystem:reset()
    self:clearAllAttacks()
    self.attackCooldowns = {}
end

return CombatDamageSystem